package com.demo.common.web.api;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.demo.common.domain.vo.BaseResult;
import com.demo.common.exception.ErrorEnums;

/**
 * BasicErrorApi
 *
 * @author demo
 * @data 2020-11-05 10:08:48
 */
@RestController
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorApi extends AbstractErrorController {

    public BasicErrorApi(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping
    public BaseResult<?> error(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus httpStatus = getStatus(request);
        ErrorEnums error = null;
        if (httpStatus.is4xxClientError()) {
            error = ErrorEnums.ILLEGAL_REQUEST;
            // 400
            if (HttpStatus.BAD_REQUEST == httpStatus) {
                // Do Nothing
            }
            // 403
            else if (HttpStatus.FORBIDDEN == httpStatus) {
                error = ErrorEnums.FORBIDDEN;
            }
            // 404
            else if (HttpStatus.NOT_FOUND == httpStatus) {
                error = ErrorEnums.RESOURCE_NOT_EXISTS;
            }
        }
        // 500
        if (httpStatus.is5xxServerError()) {
            error = ErrorEnums.SYSTEM_ERROR;
        }
        if (error == null) {
            error = ErrorEnums.UNKNOWN_ERROR;
        }
        return BaseResult.failure(error.getCode(), error.getMsg());
    }

}
